import AreaSelect from '@/components/AreaSelect';
import { addAddress } from '@/services/address';
import { getQueryParams } from '@/utils/utils';
import { Button, Form, Input, message, Modal } from 'antd';
import { useMemo, useState } from 'react';
import styles from '../index.less';

interface Props {
  visible: boolean;
  onCancel: () => void;
  style: any;
  addressModal: () => void;
  getList: () => void;
}
type AddressInfoType = {
  provinceName: string; // 省
  cityName: string; // 市
  countyName: string; // 区
};

const NewAddress: React.FC<Props> = ({ visible, onCancel, style, addressModal, getList }) => {
  const [form] = Form.useForm();
  const qs = getQueryParams();
  const { TextArea } = Input;
  // 需要的一些地址信息（其中包括省、市、区、街道、地区码等）
  const [addressInfo, setAddressInfo] = useState<AddressInfoType>({
    // ... 一些别的信息
    provinceName: '',
    cityName: '',
    countyName: '',
  });

  const { provinceName, cityName, countyName } = addressInfo;

  // 选中的值  使用的时候用 useMemo 记录一下
  const areaValue = useMemo(
    () => [provinceName, cityName, countyName],
    [provinceName, cityName, countyName],
  );

  // onChange 的回调方法
  const areaChange = (e?: string[]) => {
    // e2?: areaItemType[]   ↑
    setAddressInfo((v) => ({
      ...v,
      provinceName: e?.[0] ?? '',
      cityName: e?.[1] ?? '',
      countyName: e?.[2] ?? '',
    }));
    form.setFieldsValue({
      province: e?.[0],
      city: e?.[1],
      area: e?.[2],
    });
  };

  const confirmSubmit = async (values: any) => {
    try {
      await addAddress(values).then(() => {
        message.success('新建成功！');
        getList();
        onCancel();
        addressModal();
        onCancel();
        form.setFieldsValue({ receiptname: '', tel: '', area: [], detail: '' });
        setAddressInfo({
          provinceName: '',
          cityName: '',
          countyName: '',
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  const onFinish = async () => {
    let values = await form.validateFields();
    values.province = addressInfo.provinceName;
    values.city = addressInfo.cityName;
    values.area = addressInfo.countyName;
    values.userid = qs.id;

    Modal.confirm({
      title: '新建',
      centered: true,
      content: '是否新建地址？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => confirmSubmit(values),
    });
  };

  return (
    <Modal
      visible={visible}
      onCancel={() => {
        onCancel();
        form.setFieldsValue({ receiptname: '', tel: '', area: [], detail: '' });
        setAddressInfo({
          provinceName: '',
          cityName: '',
          countyName: '',
        });
      }}
      centered
      className={styles.manegeModal}
      footer={[
        <div className={styles.newbtn} key={'1'}>
          <Button
            onClick={() => {
              onCancel();
              form.setFieldsValue({ receiptname: '', tel: '', area: [], detail: '' });
              setAddressInfo({
                provinceName: '',
                cityName: '',
                countyName: '',
              });
            }}
            className={styles.btnCancel}
          >
            取消
          </Button>
          <Button style={style} onClick={onFinish}>
            提交
          </Button>
        </div>,
      ]}
      title="新增收货地址"
    >
      <Form
        className={styles?.formStyle}
        onFinish={onFinish}
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 28 }}
      >
        <Form.Item
          label="收货人"
          name="receiptname"
          validateTrigger="onBlur"
          rules={[
            {
              required: true,
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请输入收货人名字
                </div>
              ),
            },
            {
              pattern: new RegExp(/^[\u4e00-\u9fa5_a-zA-Z0-9]{2,10}$/),
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请输入2-10个字符（包括中文，英文字母和数字及下划线）
                </div>
              ),
            },
          ]}
        >
          <Input placeholder="请输入收货人名字" autoComplete="off" />
        </Form.Item>
        <Form.Item
          label="手机号码"
          name="tel"
          validateTrigger="onBlur"
          rules={[
            {
              required: true,
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请输入手机号码
                </div>
              ),
            },
            {
              pattern: new RegExp(/^(?:(?:\+|00)86)?1\d{10}$/),
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请输入正确的手机号
                </div>
              ),
            },
          ]}
        >
          <Input placeholder="请输入手机号码" autoComplete="off" />
        </Form.Item>
        <Form.Item
          label="所在地区"
          name="area"
          rules={[
            {
              required: true,
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请选择所在地区
                </div>
              ),
            },
          ]}
        >
          <div style={{ width: '230px' }}>
            <AreaSelect type="area" value={areaValue} onChange={areaChange} />
          </div>
        </Form.Item>
        <Form.Item
          label="详细地址"
          name="detail"
          validateTrigger="onBlur"
          rules={[
            {
              required: true,
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  请输入详细地址
                </div>
              ),
            },
            {
              pattern: new RegExp(/^[\u4e00-\u9fa5_a-zA-Z0-9]{2,120}$/),
              message: (
                <div>
                  <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                  长度需要2-120之间，不能包含特殊符号
                </div>
              ),
            },
          ]}
        >
          <TextArea
            maxLength={120}
            autoComplete="off"
            placeholder="小区楼栋/乡村名称"
            autoSize={{ minRows: 3, maxRows: 3 }}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default NewAddress;
